package com.example.controller.shopping;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.common.config.AliPayConfig;
import com.example.common.enums.RoleEnum;
import com.example.mapper.appointment.UserMapper;
import com.example.mapper.medical.DoctorMapper;
import com.example.model.entity.appointment.User;
import com.example.model.entity.medical.Doctor;
import com.example.model.entity.other.Account;
import com.example.service.shopping.OrderService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

//  https://natapp.cn/
// ekihat7647@sandbox.com
@RestController
@RequestMapping("/alipay")
public class AliPayController {

    // 支付宝沙箱网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AliPayConfig aliPayConfig;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DoctorMapper doctorMapper;

    @GetMapping("/pay")
    public void pay(Double account, Integer userId, String role, HttpServletResponse httpResponse) throws Exception {
        Account user = new Account();
        if (RoleEnum.USER.name().equals(role)) {
            user = userMapper.selectById(userId);
        } else if (RoleEnum.DOCTOR.name().equals(role)) {
            user = doctorMapper.selectById(userId);
        }

        // 1. 创建Client
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", UUID.randomUUID().toString()); // 生成一个唯一的订单号
        bizContent.set("total_amount", account); // 充值金额
        bizContent.set("subject", "账户充值 - " + user.getUsername()); // 充值名称，包括用户名
        bizContent.set("passback_params", userId + "_" + role); // 将userId和role通过passback_params传递
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY"); // 固定配置
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:8080/front/userPerson"); // 充值成功后跳转的本地页面路径
        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        if (RoleEnum.USER.name().equals(role)) {
            User u = userMapper.selectById(userId);
            u.setAccount(user.getAccount() + account);
            userMapper.updateById(u);
        } else if (RoleEnum.DOCTOR.name().equals(role)) {
            Doctor doctor = doctorMapper.selectById(userId);
            doctor.setAccount(doctor.getAccount() + account);
            doctorMapper.updateById(doctor);
        }
    }

    @PostMapping("/notify")
    public void payNotify(HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        double totalAmount = Double.parseDouble(params.get("total_amount"));
        String passbackParams = params.get("passback_params"); // 获取passback_params参数
        String[] passbackParamsArray = passbackParams.split("_"); // 假设passback_params是以"_"分隔的userId和role
        Integer userId = Integer.parseInt(passbackParamsArray[0]); // 解析userId
        String role = passbackParamsArray[1]; // 解析role
        // 根据角色和userId更新用户金额
        if (RoleEnum.USER.name().equals(role)) {
            User user = userMapper.selectById(userId);
            user.setAccount(user.getAccount() + totalAmount);
            userMapper.updateById(user);
        } else if (RoleEnum.DOCTOR.name().equals(role)) {
            Doctor doctor = doctorMapper.selectById(userId);
            doctor.setAccount(doctor.getAccount() + totalAmount);
            doctorMapper.updateById(doctor);
        }
    }
}
